package com.tanhua.server.service;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.PeachblossomApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Peachblossom;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PeachblossomVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private PeachblossomApi peachblossomApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    public void sendSoundFile(Long userId, MultipartFile soundFile) throws IOException {
        String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
        //调用api上传语音文件
        Boolean upload = peachblossomApi.sendSoundFile(userId, soundUrl);
        //判断是否上传成功
        if (!upload) {
            throw new BusinessException(ErrorResult.error());
        }
        Integer sendCount = peachblossomApi.selectSendCountInToday(userId);
        if (sendCount > 8) {
            throw new BusinessException(ErrorResult.sendError());
        }
    }


    /*桃花传音-接收语音
     * 点击接收语音按钮，随机查询一个语音消息返回，
     * 在听完语音后，可以选择喜欢或者不喜欢， //todo 是否是之前喜欢的接口
     * 如果双方互相喜欢那么可以配对成功互相关注。
     * 每日的接受数量限制（10条）
     * 对于语音，只能被一个人获取
     */

    public PeachblossomVo getpeachblossom() {
        Long userId = UserHolder.getUserId();
        //从redis中查询剩余次数
        String count = (String) redisTemplate.opsForValue().get("RemainingTimes_" + userId);
        int remainingTimes = count == null ? 10 : Integer.valueOf(count);

        // 小于等于0，抛出异常
        if (remainingTimes <= 0) {
            throw new BusinessException(ErrorResult.error()); //接受次数已用完
        }
        //随机查询一个语音消息返回但需接受用户为空
        Peachblossom peachblossom = peachblossomApi.findRandom(userId);
        //若为null，跑异常
        if (peachblossom == null) {
            throw new BusinessException(ErrorResult.error()); //
        }
        //根据userid获得userinfo信息
        UserInfo userInfo = userInfoApi.findById(peachblossom.getUserId());
        // 是否需要判断userinfo存在
        //封装vo
        PeachblossomVo vo = new PeachblossomVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setId(peachblossom.getUserId().intValue());
        vo.setSoundUrl(peachblossom.getSoundUrl());
        vo.setRemainingTimes(remainingTimes - 1);  //todo 是否需要-1
        //修改peach数据库
        peachblossom.setReceiveId(userId);
        peachblossomApi.update(peachblossom);
        //redis剩余次数-1
        //需获得当前时间距离次日还有多长时间
        // todo 定时任务每天0点清除桃花传音的redis缓存
        long timeNext = getMiol();
        redisTemplate.delete("RemainingTimes_" + userId);
        redisTemplate.opsForValue().set("RemainingTimes_" + userId, (remainingTimes - 1) + "", timeNext, TimeUnit.SECONDS);

        //返回
        return vo;

    }

    //计算第二天凌晨与当前时间的时间差秒数
    public static Long getMiol() {
        Calendar ca = Calendar.getInstance();
        //失效时间-次日0点
        ca.add(Calendar.DAY_OF_YEAR, 1);
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        long f1 = (ca.getTimeInMillis() - System.currentTimeMillis()) / 1000;
        return f1;

    }
}
